package mao.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author Totoro
 * @date 2020/7/9
 * @explain: 学习通过collections.synchronizedList对于List进行加锁。
 */
public class ConcurrentSynchronizedList {
        public static List<Integer> list =new ArrayList<>();
        public static void main(String[] args) {
            //通过创建一个类间接操作list完成的。
            //List<Integer> synchronizedList = Collections.synchronizedList(list);
            Integer b = 0;
            new Thread(new Read(list,b)).start();
            new Thread(new Write(list,b)).start();
        }
        public static class Read implements Runnable {
            List<Integer> synchronizedList;
            public Read(List<Integer> synchronizedList, Integer b) {
                super();
                this.synchronizedList = synchronizedList;

            }
            public void run() {
                while(true){
                    //必须进行加锁，否则造成concurrentModifyException
                    synchronized (synchronizedList) {
                        System.out.println("锁定同步容器");
                        try {
                            Iterator<Integer> iterator = synchronizedList.iterator();
                            Thread.sleep(1000);
                            System.out.println("开始遍历");
                            while(iterator.hasNext()) System.out.println(iterator.next());
                            System.out.println("iteration finished");
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        public static class Write implements Runnable {
            List<Integer> synchronizedList;
            public Write(List<Integer> synchronizedList, Integer b) {
                super();
                this.synchronizedList = synchronizedList;
            }
            public void run() {
                int i=0;
                while(true){
                    synchronized (synchronizedList) {
                        System.out.println("修改");
                        System.out.println("获得list锁，等待");
                        synchronizedList.add(i++);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
